package com.zhangqi.createxml;

import android.app.Activity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;

import com.zhangqi.createxml.domin.Message;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    List<Message> smsList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      //虚拟10条短信
        smsList = new ArrayList<>();
        for(int i=0;i<10;i++){
            Message sms = new Message("张琦就是牛男"+i, System.currentTimeMillis()+"", "187"+i+i, "1");
            smsList.add(sms);
        }
    }
    public void click(View v){
        //使用xml序列化器生成xml文件
        //拿到序列化器对象
        XmlSerializer xs = Xml.newSerializer();
        //2.初始化
        File file = new File("sdcard/sms.xml");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            xs.setOutput(fos,"utf-8");
            //3.开始生成xml
            //encoding:指定头节点中的encoding的属性
            xs.startDocument("utf-8", true);
            xs.startTag(null, "message");

            for(Message sms:smsList){
                xs.startTag(null,"sms");

                xs.startTag(null, "body");
                xs.text(sms.getbody());
                xs.endTag(null, "body");

                xs.startTag(null, "date");
                xs.text(sms.getdate());
                xs.endTag(null, "date");

                xs.startTag(null,"address");
                xs.text(sms.getaddress());
                xs.endTag(null, "address");

                xs.startTag(null,"type");
                xs.text(sms.gettype());
                xs.endTag(null,"type");

                xs.endTag(null,"sms");
            }

            xs.endTag(null,"message");
            //告诉序列化器生成完毕
            xs.endDocument();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
